package com.cn.wanxi.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
    /**
     * servlet 生命周期   init  service   destroy
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String path = req.getServletPath();
//        System.out.println(path);
//        必須登錄，才能放行,前提，登录页面注册页面不能过滤，直接放行
        if (path.startsWith("/back/")) {
            String username = (String) req.getSession().getAttribute("username");
            if (username == null) {
//            页面跳转
//                resp.sendRedirect("/html/login.html");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result", "notLogin");
                resp.getWriter().println(jsonObject);
            } else {
                //        放行
                filterChain.doFilter(req, resp);
            }
        } else {
            //        放行
            filterChain.doFilter(req, resp);
        }


    }

    @Override
    public void destroy() {
        System.out.println("destroy");
    }
}
